package com.piece.mall.controller;

import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.mall.model.PmsAttr;
import com.piece.mall.model.PmsSkuInfo;
import com.piece.mall.model.PmsSpuInfo;
import com.piece.mall.service.*;
import com.piece.mall.vo.SpuInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"商品spu管理"})
@RequestMapping("/api/mall/spu/info")
public class PmsSpuInfoController extends FrameWorkController {

    @Resource
    private PmsSpuInfoService pmsSpuInfoService;

    @Resource
    private PmsSkuInfoService pmsSkuInfoService;

    @Resource
    private PmsProductAttrValueService pmsProductAttrValueService;

    @Resource
    private PmsBrandService pmsBrandService;

    @Resource
    private PmsCategoryService pmsCategoryService;

    @PostMapping("/list")
    @ApiOperation(value = "查询spu列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = pmsSpuInfoService.findPage(queryTable);
        List tableData = dataTable.getData();
        List resultData = new ArrayList();
        for (Object object : tableData) {
            PmsSpuInfo spuInfo = (PmsSpuInfo) object;
            if (null != spuInfo.getBrandId()) {
                spuInfo.setBrandName(pmsBrandService.findNameById(spuInfo.getBrandId()));
            }
            if (null != spuInfo.getCatalogId()) {
                spuInfo.setCatalogName(pmsCategoryService.findNameById(spuInfo.getCatalogId()));
            }
            resultData.add(spuInfo);
        }
        return resultData;
    }

    @PostMapping("/table")
    @ApiOperation(value = "查询spu分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = pmsSpuInfoService.findPage(queryTable);
        List tableData = dataTable.getData();
        List resultData = new ArrayList();
        for (Object object : tableData) {
            PmsSpuInfo spuInfo = (PmsSpuInfo) object;
            if (null != spuInfo.getBrandId()) {
                spuInfo.setBrandName(pmsBrandService.findNameById(spuInfo.getBrandId()));
            }
            if (null != spuInfo.getCatalogId()) {
                spuInfo.setCatalogName(pmsCategoryService.findNameById(spuInfo.getCatalogId()));
            }
            resultData.add(spuInfo);
        }
        dataTable.setData(resultData);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "加载spu表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        PmsSpuInfo pmsSpuInfo = new PmsSpuInfo();
        if (id != 0) {
            pmsSpuInfo = pmsSpuInfoService.findById(id);
        }
        return success(pmsSpuInfo);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "保存spu表单数据")
    @ApiImplicitParam(value = "spu数据", dataTypeClass = SpuInfoVo.class, type = "body")
    public AjaxResponse save(@RequestBody SpuInfoVo spuInfoVo) {
        try {
            pmsSpuInfoService.saveSpuInfo(spuInfoVo);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/base_attr/update/{spuId}")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "修改商品规格参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "spuId", value = "主键", type = "path"),
            @ApiImplicitParam(value = "规格参数集合", dataTypeClass = List.class, type = "body")
    })

    public AjaxResponse updateBaseAttr(@PathVariable Long spuId, @RequestBody List<PmsAttr> attrs) {
        try {
            pmsProductAttrValueService.saveProductAttrValue(spuId, attrs);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/{spuId}/publish")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "上架spu数据")
    @ApiImplicitParam(name="id", value = "spu主键", type = "path")
    public AjaxResponse publish(@PathVariable Long spuId) {
        try {
            pmsSpuInfoService.publish(spuId);
            return success(I18nUtil.message(ExceptionConstants.MESSAGE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.MESSAGE_ERROR), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/{spuId}/cancel")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "上下架spu数据")
    @ApiImplicitParam(name="id", value = "spu主键", type = "path")
    public AjaxResponse cancel(@PathVariable Long spuId) {
        try {
            pmsSpuInfoService.cancel(spuId);
            return success(I18nUtil.message(ExceptionConstants.MESSAGE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.MESSAGE_ERROR), e.getMessage());
        }
    }

    @PostMapping("/{spuId}/detail")
    @ApiOperation(value = "查询spu详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "spuId", value = "spuId主键", type = "path"),
            @ApiImplicitParam(name = "skuId", value = "skuId主键")
    })
    public AjaxResponse spuDetail(@PathVariable Long spuId) {
        try {
            Long skuId = Convert.toLong(getRequest().getParameter("skuId"), null);
            if (null == skuId) {
                List<PmsSkuInfo> skuInfos = pmsSkuInfoService.findBySpu(spuId);
                skuId = skuInfos.get(0).getSkuId();
            }
            Map result = pmsSpuInfoService.getSpuDetail(spuId);
            Map skuResult = pmsSkuInfoService.getSkuDetail(skuId);
            result.putAll(skuResult);
            return success(result);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SERVER), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "删除spu数据")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse delete(@PathVariable Long id) throws Exception {
        pmsSpuInfoService.delete(id);
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "删除spu数据")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse deleteBatch() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            pmsSpuInfoService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }
}
